package v1

import (
	"fmt"
	"sweetsunnyflower/app/models/user_car"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type UserCarsController struct {
	Controller
}

func (ctrl *UserCarsController) Index(c *gin.Context) {

	fmt.Println(auth.CurrentUID(c))

	// 获取登录用户
	userID := auth.CurrentIntUID(c)

	userCars := user_car.GetUserCars(userID)

	response.Data(c, userCars)
}

func (ctrl *UserCarsController) Store(c *gin.Context) {

	request := requests.UserCarRequest{}
	if ok := requests.Validate(c, &request, requests.UserCarSave); !ok {
		return
	}

	userCarModel := user_car.UserCar{
		UserID:   auth.CurrentIntUID(c),
		Brand:    request.Brand,
		Color:    request.Color,
		Plate:    request.Plate,
		Sites:    request.Sites,
		UseYears: request.UseYears,
	}
	userCarModel.Create()
	if userCarModel.ID > 0 {
		response.Created(c, userCarModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *UserCarsController) Update(c *gin.Context) {

	userCarModel := user_car.Get(c.Param("id"))
	if userCarModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserCar(c, userCarModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.UserCarRequest{}
	if ok := requests.Validate(c, &request, requests.UserCarSave); !ok {
		return
	}

	userCarModel.Brand = request.Brand
	userCarModel.Color = request.Color
	userCarModel.Plate = request.Plate
	userCarModel.Sites = request.Sites
	userCarModel.UseYears = request.UseYears

	rowsAffected := userCarModel.Save()
	if rowsAffected > 0 {
		response.Data(c, userCarModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *UserCarsController) Delete(c *gin.Context) {

	userCarModel := user_car.Get(c.Param("id"))
	if userCarModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserCar(c, userCarModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := userCarModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
